package Thread;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/7/9 16:58
 * @description：
 * @modified By：
 * @version:
 */
class  MyBlockingQueue1{
    private String[] data=null;
    private int head=0;
    private int tail =0;
    //元素个数
    private int size=0;
    public MyBlockingQueue1(int capacity){
        data=new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
       synchronized (this) {
           //队满，开始阻塞
           while (size>=data.length)
           {
        //   return;
               this.wait();
       }
           data[tail]=elem;
           tail++;
           if (tail>=data.length){
               tail=0;
           }
           size++;
           this.notify();
       }

       }


    public String take() throws InterruptedException {
    synchronized (this){
        //队空开始阻塞
        while (size==0){
            //
            //return null;
            this.wait();
        }
        String ret=data[head];
        head++;
        if (head>=data.length){
            head=0;
        }
        size--;
        this.notify();
        return ret;
    }
    }

}
public class Demo20 {
    public static void main(String[] args) {
        MyBlockingQueue1 queue=new MyBlockingQueue1(1000);
        Thread producer=new Thread(()->{
            int n=0;
            while (true){
                try {
                    queue.put(n+" ");
                    System.out.println("生产元素： "+n);
                    n++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread consumer=new Thread(()->{
            while (true){
                String n=null;
                try {
                    n= queue.take();
                    System.out.println("消费元素： "+n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();
        consumer.start();
    }
}